const {extractVerificationCode } = require('../utils/utils.js');//引用工具类

/**
 * 获取邮箱验证码
 * @param {*} page
 * @param {*} emailIndex
 * @returns
 */
const getVerificationCode = async (borwser, email) => {
    const page = await borwser.newPage();
    await page.goto('https://www.microsoft.com/zh-cn/microsoft-365/outlook/email-and-calendar-software-microsoft-outlook',
      {timeout: 120000});
    const page1Promise = page.waitForEvent('popup');
    await page.locator('#action-oc5b26').click();
    const page1 = await page1Promise;
    await page1.waitForTimeout(5000);
    await page1.getByRole('textbox', { name: '请输入电子邮件、电话或 Skype。' }).click();
    await page1.getByRole('textbox', { name: '请输入电子邮件、电话或 Skype。' }).fill(email);
    await page1.getByRole('button', { name: '下一步' }).click();
    // const emailList0 = await page1.locator('div[title="删除"]').all();
    // if (emailList0.length <= 0) {
    //   await page1.waitForTimeout(5000);
    //   await page1.getByRole('textbox', { name: '密码' }).click();
    //   await page1.getByRole('textbox', { name: '密码' }).fill('Wcj877099858');
    //   await page1.getByTestId('primaryButton').click();
    //   await page1.waitForTimeout(5000);
    //   await page1.getByTestId('primaryButton').click();
    // }
    await page1.waitForTimeout(5000);
    await page1.getByLabel('文件夹').getByText('收件箱').click();
    await page1.waitForTimeout(5000);
    console.log('开始获取验证码')
    const emailList = await page1.locator('div[title="删除"]').all();
    console.log(emailList.length)
    for (const email of emailList) {
      const secondParentByXPath = email.locator('xpath=../../../../..'); // 
      await secondParentByXPath.click();
      await page1.waitForSelector('[aria-label="电子邮件"]', {
        state: 'visible',
        timeout: 50000
      })
      const content = await page1.locator('[aria-label="邮件正文"]').innerText();
      const code = extractVerificationCode(content);
      if (code) {
        console.log('验证码：', code);
        await page1.close();
        await page.close();
        return code;
      }
    }
};

module.exports = { getVerificationCode };